<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>咨询管理 - 商户端</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .chat-container {
            max-width: 1400px;
            margin: 20px auto;
            height: calc(100vh - 200px);
            display: flex;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
        }
        .chat-sidebar {
            width: 350px;
            border-right: 1px solid #dee2e6;
            background-color: #f8f9fa;
            overflow-y: auto;
        }
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid #dee2e6;
            background-color: #fff;
        }
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f8f9fa;
        }
        .chat-input-area {
            padding: 15px 20px;
            border-top: 1px solid #dee2e6;
            background-color: #fff;
        }
        .message {
            margin-bottom: 15px;
            display: flex;
        }
        .message.user {
            justify-content: flex-end;
        }
        .message.merchant {
            justify-content: flex-start;
        }
        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;
        }
        .message.user .message-content {
            background-color: #28a745;
            color: white;
        }
        .message.merchant .message-content {
            background-color: white;
            color: #333;
            border: 1px solid #dee2e6;
        }
        /* 商家端：用户的消息显示在左边，商家的消息显示在右边 */
        /* 所以这里user类表示商家自己的消息（右边），merchant类表示用户的消息（左边） */
        .message-time {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }
        .session-item {
            padding: 15px;
            border-bottom: 1px solid #dee2e6;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .session-item:hover {
            background-color: #e9ecef;
        }
        .session-item.active {
            background-color: #28a745;
            color: white;
        }
        .session-item.active .session-product {
            color: rgba(255,255,255,0.9);
        }
        .session-item.active .session-last-message {
            color: rgba(255,255,255,0.8);
        }
        .session-product {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .session-last-message {
            font-size: 12px;
            color: #6c757d;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .unread-badge {
            background-color: #dc3545;
            color: white;
            border-radius: 10px;
            padding: 2px 8px;
            font-size: 11px;
            margin-left: 5px;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container-fluid">
        <div class="row">
            <jsp:include page="../common/sidebar.jsp"/>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="pt-3">
                    <h1 class="h2 mb-4">咨询管理</h1>
                    
                    <c:if test="${error != null}">
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            ${error}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </c:if>
                    
                    <div class="chat-container">
                        <!-- 左侧会话列表 -->
                        <div class="chat-sidebar">
                            <h5 class="p-3 mb-0 border-bottom">咨询列表</h5>
                            <div id="sessionList">
                                <c:forEach var="session" items="${sessions}">
                                    <div class="session-item" 
                                         data-session-id="${session.sessionId}"
                                         data-user-id="${session.userId}"
                                         onclick="loadSession('${session.sessionId}', '${session.productName}', '${session.userId}')">
                                        <div class="session-product">
                                            ${session.user != null ? session.user.username : '未知用户'}
                                            <c:if test="${session.unreadCountMerchant > 0}">
                                                <span class="unread-badge">${session.unreadCountMerchant}</span>
                                            </c:if>
                                        </div>
                                        <div class="session-last-message">${session.lastMessage != null ? session.lastMessage : '暂无消息'}</div>
                                        <div class="session-last-message">
                                            <fmt:formatDate value="${session.lastMessageTime}" pattern="yyyy-MM-dd HH:mm"/>
                                        </div>
                                    </div>
                                </c:forEach>
                                <c:if test="${empty sessions}">
                                    <div class="text-center text-muted p-4">暂无咨询</div>
                                </c:if>
                            </div>
                        </div>
                        
                        <!-- 右侧聊天区域 -->
                        <div class="chat-main">
                            <div class="chat-header">
                                <h5 id="chatTitle">请选择咨询会话</h5>
                            </div>
                            <div class="chat-messages" id="chatMessages">
                                <div class="text-center text-muted mt-5">
                                    <p>请选择左侧的咨询会话</p>
                                </div>
                            </div>
                            <div class="chat-input-area" id="chatInputArea" style="display: none;">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="messageInput" placeholder="输入消息..." 
                                           onfocus="clearUnreadCount()">
                                    <button class="btn btn-success" onclick="sendMessage()">发送</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let ws = null;
        let currentSessionId = null;
        let currentProductName = null;
        let currentUserId = null;
        const merchantId = ${sessionScope.merchant.userId};
        const userType = 1; // 商家类型：1
        
        // 加载会话
        function loadSession(sessionId, productName, userId) {
            currentSessionId = sessionId;
            currentProductName = productName;
            currentUserId = userId;
            
            // 更新UI
            document.getElementById('chatTitle').textContent = '咨询：' + productName;
            document.getElementById('chatInputArea').style.display = 'block';
            
            // 更新会话列表选中状态
            document.querySelectorAll('.session-item').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-session-id') === sessionId) {
                    item.classList.add('active');
                }
            });
            
            // 连接WebSocket
            connectWebSocket();
            
            // 加载历史消息（会自动清除未读）
            loadHistoryMessages();
        }
        
        // 连接WebSocket
        function connectWebSocket() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.close();
            }
            
            // 根据当前页面协议选择ws://或wss://
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = protocol + '//' + window.location.host + '${pageContext.request.contextPath}/chat/' + merchantId + '/' + userType + '/' + currentSessionId;
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                console.log('WebSocket连接已建立');
            };
            
            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                handleMessage(message);
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
            };
            
            ws.onclose = function() {
                console.log('WebSocket连接已关闭');
            };
        }
        
        // 处理接收到的消息
        function handleMessage(message) {
            if (message.type === 'message') {
                // 商家端：用户的消息显示在左边（merchant类），商家的消息显示在右边（user类）
                displayMessage(message.content, message.senderType === 0 ? 'merchant' : 'user', new Date(message.createTime));
            } else if (message.type === 'ack') {
                console.log('消息发送成功:', message.messageId);
            } else if (message.type === 'error') {
                alert('错误：' + message.message);
            }
        }
        
        // 发送消息
        function sendMessage() {
            const content = document.getElementById('messageInput').value.trim();
            
            if (!content) {
                alert('请输入消息内容');
                return;
            }
            
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                alert('连接未建立，请稍候再试');
                return;
            }
            
            // 从sessionId解析productId
            const parts = currentSessionId.split('_');
            const productId = parts[2];
            
            const message = {
                type: 'message',
                content: content,
                productId: productId,
                productName: currentProductName
            };
            
            ws.send(JSON.stringify(message));
            
            // 显示自己发送的消息（商家端：商家自己的消息显示在右边，用user类）
            displayMessage(content, 'user', new Date());
            
            // 清空输入框
            document.getElementById('messageInput').value = '';
        }
        
        // 显示消息
        function displayMessage(content, senderType, time) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + senderType;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;
            
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = formatTime(time);
            
            contentDiv.appendChild(timeDiv);
            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);
            
            // 滚动到底部
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 清除未读消息数
        function clearUnreadCount() {
            if (!currentSessionId) {
                return;
            }
            
            // 调用后端清除未读（如果还没有清除的话）
            fetch('${pageContext.request.contextPath}/merchant/consultation?action=clearUnread&sessionId=' + currentSessionId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 更新UI中的未读数量
                        const sessionItem = document.querySelector(`[data-session-id="${currentSessionId}"]`);
                        if (sessionItem) {
                            const badge = sessionItem.querySelector('.unread-badge');
                            if (badge) {
                                badge.remove();
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('清除未读失败:', error);
                });
        }
        
        // 加载历史消息
        function loadHistoryMessages() {
            if (!currentSessionId) {
                return;
            }
            
            fetch('${pageContext.request.contextPath}/merchant/consultation?action=history&sessionId=' + currentSessionId)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.messages) {
                        const messagesDiv = document.getElementById('chatMessages');
                        messagesDiv.innerHTML = '';
                        data.messages.forEach(msg => {
                            // 商家端：用户的消息显示在左边（merchant类），商家的消息显示在右边（user类）
                            displayMessage(msg.content, msg.senderType === 0 ? 'merchant' : 'user', new Date(msg.createTime));
                        });
                        
                        // 加载历史消息后清除未读（因为后端已经清除了）
                        const sessionItem = document.querySelector(`[data-session-id="${currentSessionId}"]`);
                        if (sessionItem) {
                            const badge = sessionItem.querySelector('.unread-badge');
                            if (badge) {
                                badge.remove();
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('加载历史消息失败:', error);
                });
        }
        
        // 格式化时间
        function formatTime(date) {
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return hours + ':' + minutes;
        }
        
        // 回车发送消息
        document.getElementById('messageInput')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>

